<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-row :gutter="20"><!-- gutter是指定每个分栏的间隔 -->
                <!-- 分栏一共占24格，给搜索框7格，添加按钮4格 -->
<!--                <el-col :span="7">-->
<!--                    &lt;!&ndash; 搜索与添加区域 &ndash;&gt;-->
<!--                    <div style="display: flex; align-items: center;">-->
<!--                      <el-input placeholder="请输入内容" clearable @clear="getUsers()" v-model="queryInfo.query"></el-input>-->
<!--                      <el-button type="primary" size="mini" @click="getUsers()"><el-icon><Search /></el-icon></el-button>-->
<!--                    </div>-->
<!--                </el-col>-->
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table v-loading="loading" :data="rolesList" border stripe>
              <!-- 展开列 -->
                  <el-table-column type="index"></el-table-column>
                  <el-table-column label="角色名称" prop="role"></el-table-column>
                  <el-table-column label="角色等级" prop="rolegrade"></el-table-column>
                  <el-table-column label="操作" width="300px">
                      <template #default="scope">
                          <!-- 放置修改、删除和分配角色按钮 -->
                          <el-button type="primary"  size="mini" @click="showEditDialog(scope.row.role)"><el-icon><Edit /></el-icon>编辑</el-button>
                          <el-button type="danger"  size="mini" @click="removeRoleById(scope.row)"><el-icon><Delete /></el-icon>删除</el-button>
                          <el-button type="warning"  size="mini" @click="showSetRightDialog(scope.row)"><el-icon><Setting /></el-icon>分配权限</el-button>
                      </template>
                      </el-table-column>
                      </el-table>
                    <!-- 添加用户的对话框 -->
                    <el-dialog title="添加用户" v-model="addDialogVisible" width="20%" @close="addDialogClosed">
                    <!-- 内容主体区 -->
                    <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="70px">
                      <el-form-item label="角色名" prop="rolename"> <!-- prop是验证规则属性 -->
                        <el-input v-model="addRoleForm.rolename"></el-input>
                      </el-form-item>
                      <el-form-item label="等级名称" prop="grade">
                        <el-input v-model="addRoleForm.rolegrade"></el-input>
                      </el-form-item>
                      <el-form-item label="等级" prop="grade">
                        <el-input v-model="addRoleForm.grade" placeholder="例如：1,2,3,4"></el-input>
                      </el-form-item>
                    </el-form>
                    <!-- 底部区 -->
                      <template #footer>
                        <span class="dialog-footer">
                          <el-button @click="addDialogVisible = false">取 消</el-button>
                          <el-button type="primary" @click="addrole()">确 定</el-button>
                        </span>
                      </template>
                  </el-dialog>
                      <el-dialog title="分配权限" v-model="setRightDialogVisible" width="20%">
                          <!-- 树形组件 -->
                          <el-tree :data="rightsList" :props="treeProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defkeys" ref="treeRef"></el-tree>
                          <template #footer>
                              <span class="dialog-footer">
                                  <el-button @click="setRightDialogVisible = false">取 消</el-button>
                                  <el-button type="primary" @click="allotRights()">确 定</el-button>
                              </span>
                          </template>
                      </el-dialog>
                    <!-- 修改角色的对话框 -->
          <el-dialog title="修改用户" v-model="editDialogVisible" width="20%" @close="editDialogClosed"
          :close-on-click-modal='false'>
            <!-- 内容主体区 -->
            <el-form :model="editroleForm" :rules="editroleFormRules" ref="editroleFormRef" label-width="70px">
              <el-form-item label="角色名" prop="rolename">
                <el-input v-model="editroleForm.role"></el-input>
              </el-form-item>
              <el-form-item label="角色等级" prop="grade">
                <el-input v-model="editroleForm.rolegrade"></el-input>
              </el-form-item>
              <el-form-item label="级别" prop="grade">
                <el-input v-model="editroleForm.grade"></el-input>
              </el-form-item>
            </el-form>
            <!-- 底部区 -->
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="editDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="editrole()">确 定</el-button>
                </span>
              </template>
          </el-dialog>
          </el-card>
    </div>
</template>

<script>
import { defineComponent } from 'vue'
import { Delete, Setting, Edit } from '@element-plus/icons-vue'
import {
  ElTable,
  ElTableColumn,
  ElButton,
  ElInput,
  ElDialog,
  ElForm,
  ElFormItem,
  ElTree,
  ElMessage,
  ElMessageBox
} from 'element-plus'

export default defineComponent({
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
    ElInput,
    ElDialog,
    ElForm,
    ElFormItem,
    ElTree,
    Delete,
    Setting,
    Edit
  },
  data() {
    return {
      loading:false,
      // 新增角色数据
      addRoleForm: {},
      editroleForm: {},
      // 角色列表
      rolesList: [],
      // 控制添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      editDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'menus',
        children: 'children'
      },
      // 默认选中的权限 ID 数组对象
      defkeys: [],
      // 当前即将分配权限的角色 ID
      roleId: ''
    }
  },
  created() {
    // 获取所有的角色信息
    this.getRolesList()
  },
  methods: {
    // 监听添加角色对话框的关闭状态
    addDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },

    // 关闭编辑用户的对话框
    editDialogClosed() {
      this.$refs.editroleFormRef.resetFields()
    },

    // 点击按钮，保存编辑
    async editrole() {
      try {
        const response = await this.$http.post("/editrole/", this.editroleForm)
          console.log(response)
        this.editDialogVisible = false;
        ElMessage.success('编辑用户成功！');
        this.getRolesList()
      } catch (error) {
        console.log(error)
        ElMessage.error('编辑用户失败！');
      }
    },
    // 获取角色列表
    async getRolesList() {
      this.loading = true
      try {
        const response = await this.$http.get('/getrole/')
        this.loading = false
        if (response.status === 200) {
          this.rolesList = response.data;
          // ElMessage.success('更新角色列表成功！');
        } else {
          ElMessage.error('更新角色列表失败！');
        }
      } catch (error) {
        console.log(error)
        this.getRolesList()
        // ElMessage.error('更新角色列表失败！');
      }
    },
    // 展示编辑用户的对话框
    async showEditDialog(role) {
      try {
        const response = await this.$http.post('/showroleEdit/', {'role': role})
        this.editroleForm = response.data;
        this.editDialogVisible = true;
        ElMessage.success('打开成功！');
      } catch (error) {
        console.error(error);
        ElMessage.error('打开失败！');
      }
    },
    // 根据角色名删除对应用户信息
    async removeRoleById(role) {
      // 弹框询问用户是否删除数据
      ElMessageBox.confirm('此操作将永久删除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = { 'role': role.role }
        try {
          const response = await this.$http.post('/delrole/', data)
          console.log(response)
          this.getRolesList()
          ElMessage.success('删除成功!');
        } catch (error) {
          console.error(error)
          ElMessage.error('删除失败！');
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      })
    },

    // 展示权限分配的对话框
    async showSetRightDialog(role) {
      this.defkeys = []; // 清空数组
      this.roleId = role.role;
      try {
        const response = await this.$http.post('/showaddmenus/', {'role': this.roleId});
        // 把获取到的权限数据保存到data中
        this.rightsList = response.data.all;
        // 递归获取三级节点的ID
        this.defkeys = response.data.exist;
        // 显示对话框
        this.setRightDialogVisible = true;
        ElMessage.success('获取权限成功!');
      } catch (error) {
        console.error(error)
        ElMessage.error('获取权限失败！');
      }
    },

    // 点击为角色分配权限
    async allotRights() {
      // “...”为“展开运算符”，将一个数组转为用逗号分隔的参数序列
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");
      console.log(idStr);
      try {
        const response = await this.$http.post('/addmenus/', {'rids': idStr, 'role': this.roleId});
        console.log(response);
        ElMessage.success('更新权限成功!');
        // 重新刷新角色列表
        this.getRolesList();
        // 关闭对话框
        this.setRightDialogVisible = false;
      } catch (error) {
        console.error(error)
        ElMessage.error('更新权限失败！');
      }
    },

    // 点击按钮，添加新角色
    async addrole() {
      try {
        const response = await this.$http.post("/addrole/", this.addRoleForm);
        console.log(response);
        this.addRoleForm = {}
        this.addDialogVisible = false;
        ElMessage.success('添加角色成功！');
        this.getRolesList();
      } catch (error) {
        console.log(error);
        ElMessage.error('添加角色失败！');
      }
    }
  }
})
</script>

<style scoped>
.el-tag {
    margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
</style>